
#include "mainwindow.h"
#include "dialog/vcpkginstalldialog.h"
#include "ui_mainwindow.h"

#include <QDir>
#include <QFileDialog>
#include <QProcess>

#include <config/config.h>

#define KEY_PACKAGE 990
#define KEY_VERSION 991
#define KEY_DETAIL  992

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->splitter->setSizes(QList<int>() << 150 << 400);


    // [1] vcpkg list
    if (Config::getAppVCPkgConfig().isEmpty())
    {
        ui->statusbar->showMessage("提示：未配置 vcpkg 路径");
    }
    else
    {
        ui->statusbar->showMessage("已配置路径: " + Config::getAppVCPkgConfig());
    }

    reload_vcpkg_list();


    // [2] vcpkg search
    ui->splitter_3->setSizes(QList<int>() << 150 << 400);
    ui->vcpkg_search_tablewidget->horizontalHeader()->setStretchLastSection(true);
    ui->vcpkg_search_tablewidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::Interactive);
    ui->vcpkg_search_tablewidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->vcpkg_search_tablewidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->vcpkg_search_tablewidget->setSelectionMode(QAbstractItemView::SingleSelection);
    //    ui->tableWidget->verticalHeader()->hide();
    //    connect(ui->tableWidget, &QTableWidget::itemDoubleClicked, this, &RecordSelectorDialog::slotItemDoubleClicked);

    reload_vcpkg_search();

    if (Config::getAppCMakeConfig().isEmpty() == false) {
        auto dir = QFileInfo().absolutePath();
        qputenv("PATH", qEnvironmentVariable("PATH").prepend(dir + ":").toUtf8());
    }
}

MainWindow::~MainWindow()
{

}

void MainWindow::reload_vcpkg_list()
{
    if (Config::getAppVCPkgConfig().isEmpty())
        return;

    ui->vcpkg_list_widget->clear();

    QProcess vcpkg;
    vcpkg.setProgram(Config::getAppVCPkgConfig());
    vcpkg.setArguments(QStringList() << "list");
    vcpkg.start();
    vcpkg.waitForFinished();

    QString output = vcpkg.readAllStandardOutput();
    foreach (QString line, output.split("\n"))
    {
        if (line.length() > 50)
        {
            // ui->vcpkg_list_widget->addItem(line.mid(0, 50).trimmed());
            QListWidgetItem *item = new QListWidgetItem;
            auto pkg = line.mid(0, 49).trimmed();
            auto ver = line.mid(50, 19).trimmed();
            auto dea = line.mid(70).trimmed();

            item->setData(KEY_PACKAGE, pkg);
            item->setData(KEY_VERSION, ver);
            item->setData(KEY_DETAIL,  dea);
            item->setText(line.mid(0, 50).trimmed());
            ui->vcpkg_list_widget->addItem(item);
        }
    }

    ui->vcpkg_list_content->setPlainText(output);
}

void MainWindow::reload_vcpkg_search(const QString &text)
{
    if (Config::getAppVCPkgConfig().isEmpty())
        return;

    ui->vcpkg_search_content->clear();
    ui->vcpkg_search_tablewidget->clearContents();
    ui->vcpkg_search_tablewidget->setRowCount(0);

    auto process = new QProcess;
    process->setProgram(Config::getAppVCPkgConfig());
    process->setArguments(QStringList() << "search" << ui->vcpkg_search_edit->text());
    connect(process, &QProcess::readyReadStandardOutput, [this, process]()
    {
        QString output = process->readAllStandardOutput();
        ui->vcpkg_search_content->append(output);

        foreach (auto line, output.split("\n"))
        {
            if (output.trimmed().isEmpty())
            {
                continue;
            }
            if (line.split(" ").first().contains("["))
            {
                continue;
            }

            auto splits = line.split(QRegExp("(\\s+){2,}"));
            if (splits.length() == 3)
            {
                auto item_package = new QTableWidgetItem;
                auto item_version = new QTableWidgetItem;
                auto item_descript = new QTableWidgetItem;

                item_package->setText(splits.at(0));
                item_version->setText(splits.at(1));
                item_descript->setText(splits.at(2));

                int row = ui->vcpkg_search_tablewidget->rowCount();
                ui->vcpkg_search_tablewidget->setRowCount(row + 1);
                ui->vcpkg_search_tablewidget->setItem(row, 0, item_package);
                ui->vcpkg_search_tablewidget->setItem(row, 1, item_version);
                ui->vcpkg_search_tablewidget->setItem(row, 2, item_descript);
            }
        }
    });

    connect(process, QOverload<int>::of(&QProcess::finished), [this](int)
    {
        ui->vcpkg_search_result_lab->setText(QString("结果: %1").arg(ui->vcpkg_search_tablewidget->rowCount()));
    });

    process->start();
}

void MainWindow::on_vcpkg_list_reload_btn_clicked()
{
    reload_vcpkg_list();
}

void MainWindow::on_action_vcpkg_triggered()
{
    QString filename = QFileDialog::getOpenFileName(nullptr, "", "", "vcpkg vcpkg.exe");
    if (filename.isEmpty() == false)
    {
        Config::setAppVCPkgConfig(filename);
        ui->statusbar->showMessage("已配置路径: " + filename);
    }
}

void MainWindow::on_action_cmake_triggered()
{
    QString filename = QFileDialog::getOpenFileName(nullptr, "", "", "cmake cmake.exe");
    if (filename.isEmpty() == false)
    {
        Config::setAppCMakeConfig(filename);
        ui->statusbar->showMessage("已配置路径: " + filename);
    }
}

void MainWindow::on_vcpkg_list_widget_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    if (current)
    {
        QProcess vcpkg;
        vcpkg.setProgram(Config::getAppVCPkgConfig());
        vcpkg.setArguments(QStringList() << "install" << current->text());
        vcpkg.start();
        vcpkg.waitForFinished();

        QString output = vcpkg.readAllStandardOutput();
        ui->vcpkg_install_content->setPlainText(output);

        ui->lab_package->setText(current->data(KEY_PACKAGE).toString());
        ui->lab_version->setText(current->data(KEY_VERSION).toString());
        ui->lab_detail->setText(current->data(KEY_DETAIL).toString());
    }
}


void MainWindow::on_vcpkg_search_textChanged(const QString &arg1)
{
    int rows = ui->vcpkg_list_widget->count();

    if (arg1.isEmpty())
    {
        for (int row = 0; row < rows; ++row)
        {
            auto item = ui->vcpkg_list_widget->item(row);
            if (item) item->setHidden(false);
        }
        return;
    }

    for (int row = 0; row < rows; ++row)
    {
        auto item = ui->vcpkg_list_widget->item(row);
        if (item)
            item->setHidden(true);
    }

    auto items = ui->vcpkg_list_widget->findItems(arg1, Qt::MatchContains);
    foreach (auto item, items)
    {
        if (item)
            item->setHidden(false);
    }
}

void MainWindow::on_vcpkg_search_edit_textChanged(const QString &arg1)
{
    vcpkg_search_timer.stop();
    vcpkg_search_timer.disconnect();
    vcpkg_search_timer.setInterval(500);

    connect(&vcpkg_search_timer, &QTimer::timeout, this, [this, arg1]()
    {
        vcpkg_search_timer.stop();
        reload_vcpkg_search(arg1);
    });

    vcpkg_search_timer.start();
}


void MainWindow::on_vcpkg_search_tablewidget_customContextMenuRequested(const QPoint &pos)
{
    QMenu context;
    auto install_action = context.addAction("安装", [this]()
    {
        auto item = ui->vcpkg_search_tablewidget->currentItem();
        if (item)
        {
            auto pkg = ui->vcpkg_search_tablewidget->item(item->row(), 0)->text();
            VCPkgInstallDialog dialog;
            dialog.setWindowTitle("vcpkg 正在安装：" + pkg);
            dialog.setInstallPkg(pkg);
            dialog.start();
            dialog.exec();
            reload_vcpkg_list();
        }
    });
    install_action->setEnabled(ui->vcpkg_search_tablewidget->currentItem());
    context.exec(QCursor::pos());
}

